<template>
	
	 
	    <div>
		 <a-divider  orientation="left">权限设置</a-divider>
	      <a-tree checkable 
		  showLine 
		  :auto-expand-parent="autoExpandParent"
			:blockNode="true" 
	       v-model="checkData" 
		   :tree-data="treeData" 
		   :replaceFields="replaceFields" 
		   @check="onCheck" />
	       
	    </div>
	  
	  
 
</template>
<script>
	import {rolePermission} from '../public/http.js';

	export default {
	props: ['menuIds', 'roleId'],
	data() {
		return {
			autoExpandParent: true,
		 
			treeData: [],
			checkData: [],
			replaceFields: {
				children: 'children',
				title: 'name',
				key: 'id'
			}
		};
	},

	methods: {
		//搜索当前权限，获得所有父级权限id
		//查找父节点
		// 查找一个树多有第一个节点，深度遍历
		getFirstNode(tree) {
			var temp = [];
			var forFn = data => {
				for (let i = 0; i < data.length; i++) {
					if (data[i].children) {
						//如果数据存在子级 那么把当前数据的ID存入返回数组内
						temp.push(data[i].id);
						forFn(data[i].children);
					}
				}
			};

			forFn(tree);
			return temp;
		},

		getTree() {
			rolePermission(this.roleId).then(res => {
				let data = res.data.tree;
				this.treeData =data;
				let ids = this.getFirstNode(data);
				let hasMenus = res.data.menus;
				if (hasMenus) {
					//历史数据回显回去
					this.$emit('onCheck', hasMenus);
					//过滤掉所有父级以后的数据选选项				

					//获取需要显示的数据
					this.checkData = hasMenus.filter(item => {
						return !ids.includes(item)
					});
					
				}
			});
		},
		onCheck(val, event) {
			let data = [...val, ...event.halfCheckedKeys];
			this.$emit('onCheck', data);
		}
	},
	created() {
		this.getTree();
	},
};
</script>
